<template>
  <div>
    <van-nav-bar left-arrow title="搜索中心" @click-left="$router.back()">
    </van-nav-bar>

    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @input="hGetSuggestion"
    >
      <!-- <div slot="action">搜索</div> -->
      <!-- 插槽新语法 -->
      <template #action>
        <div @click="doSearch">搜索</div>
      </template>
    </van-search>

    <!-- 联想建议区域 -->
    <van-cell-group v-if="keyword">
      <van-cell v-for="(item,index) in wrapperList"
        :key="index"
        icon="search"
        @click="suggestSearch(index)">
        <div v-html="item"></div>
        </van-cell>
    </van-cell-group>

    <!-- 搜索历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"> </van-cell>
      <van-cell
      v-for="(item,index) in deHistoryList"
      :title="item"
      :key="index"
      >
        <van-icon name="close" @click="delHistory(index)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search'
import { setItem, getItem } from '@/store/ls'
import _ from 'lodash'
// console.log(_)
export default {
  name: 'Search',
  data () {
    return {
      keyword: '', // 搜索关键字
      suggestList: [], // 搜索建议列表
      historyList: getItem('his') || [] // 搜索历史列表
    }
  },
  computed: {
    wrapperList () {
      const list = this.suggestList.map((str) => {
        const reg = new RegExp(this.keyword, 'gi')
        const wrapperStr = str.replace(reg, (target) => {
          return `<span style="color:red">${target}</span>`
        })
        return wrapperStr
      })
      return list
    },
    // 历史列表去重
    deHistoryList () {
      return Array.from(new Set(this.historyList))
    }
  },
  methods: {
    // 根据搜索关键字发请ajax请求获取搜索列表数据
    // 1.包装的位置 要写到回调函数的外层
    // 2.this的指向问题,不能写成箭头函数
    hGetSuggestion: _.debounce(function () {
      // 做空串判断
      if (this.keyword === '') {
        this.suggestList = []
        return
      }
      getSuggestion(this.keyword).then(res => {
        console.log(res)
        this.suggestList = res.data.data.options
      })
    }, 260),

    // 搜索按钮点击
    doSearch () {
      // 将当前关键词存入本地
      this.historyList.push(this.keyword)
      // 存入本地
      setItem('his', this.historyList)
    },
    // 搜索建议区域点击
    suggestSearch (index) {
      this.historyList.push(this.suggestList[index])
      setItem('his', this.historyList)
    },
    // 删除历史记录
    delHistory (index) {
    // 1.在historyList中删除
      this.historyList.splice(index, 1)
      // 2.同步一下本地存储
      setItem('his', this.historyList)
    },
    isAdd (str) {
      const index = this.historyList.findIndex(item => item === str)
      return index !== -1
    }
  }

}
</script>
